package com.example.demo.service.impl;

import com.example.demo.entity.Admin;
import com.example.demo.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.slf4j.Logger; // 建议添加日志
import org.slf4j.LoggerFactory; // 建议添加日志

import java.util.HashSet;
import java.util.Set;

@Service("adminDetailsServiceImpl") // 明确 Bean 名称，便于在 SecurityConfig 中引用
public class AdminDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(AdminDetailsServiceImpl.class);

    private final AdminRepository adminRepository;

    @Autowired
    public AdminDetailsServiceImpl(AdminRepository adminRepository) {
        this.adminRepository = adminRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        log.debug("尝试加载管理员用户: {}", account);
        Admin admin = adminRepository.findByAccount(account)
                .orElseThrow(() -> {
                    log.warn("未找到管理员账户: {}", account);
                    return new UsernameNotFoundException("Admin not found with account: " + account);
                });

        // 为管理员赋予 "ROLE_ADMIN" 权限
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        // 如果有其他权限，例如基于数据库的角色表，可以在这里动态加载

        // 关键: admin.getPassword() 返回的是从数据库中获取的密码。
        // 由于我们配置了 PlainTextPasswordEncoder，这里返回的明文密码将直接用于比较。
        log.info("管理员 {} 加载成功，准备进行认证。", account);
        return new User(admin.getAccount(), admin.getPassword(), authorities);
    }
}
